package org.basis.groovy.classpath.helper;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.basis.enhance.groovy.helper.RegisterScriptHelper;
import org.basis.enhance.groovy.loader.ScriptLoader;
import org.basis.enhance.groovy.registry.ScriptRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;

import java.util.Map;

/**
 * 注册脚本到ClassPath中helper
 *
 * @author wenpan 2022/10/01 19:13
 */
@Slf4j
public class RegisterScriptToClasspathHelper implements RegisterScriptHelper {


    @Autowired
    private ScriptLoader scriptLoader;

    @Autowired
    private ScriptRegistry scriptRegistry;

    //TODO
    @Override
    public boolean registerScript(@NonNull String name, @NonNull String content, boolean allowCover) throws Exception {
        log.warn("start manual register script, name is : [{}], script content is : {}", name, content);
        if (StringUtils.isBlank(name) || StringUtils.isBlank(content)) {
            throw new IllegalArgumentException("name and content can not be null.");
        }
        return true;
    }

    @Override
    public boolean batchRegisterScript(@NonNull Map<String, String> scriptMap, boolean allowCover) {
        log.warn("batch register script start.");
        scriptMap.forEach((name, content) -> {
            try {
                registerScript(name, content, allowCover);
            } catch (Exception e) {
                throw new RuntimeException("register failed，please retry.", e);
            }
        });
        log.warn("batch register script success.");
        return true;
    }
}
